package com.py.credit.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.constant.RecordStatusEnum;
import com.py.credit.dao.SContentDao;
import com.py.credit.dao.SContentInfoDao;
import com.py.credit.entity.Column;
import com.py.credit.entity.DataResult;
import com.py.credit.entity.SContentInfo;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TableResult;
import com.py.credit.entity.common.TreeObj;
import com.py.credit.service.ScontentService;
import com.py.credit.service.ShareResourceService;
import com.py.credit.service.TableService;
import com.py.framework.core.common.Page;

@Service
public class ScontentServiceImpl implements ScontentService {

	@Autowired
	private SContentDao sContentDao;

	@Autowired
	private SContentInfoDao sContentInfoDao;
	@Autowired
	private TableService tableService;

	@Autowired
	private ShareResourceService shareResourceService;

	@Override
	@Transactional
	public void add(SContentInfo sContentInfo, List<TreeObj> nodeList) {

		int tableNum = 0;

		int categoryNum = 0;

		int colNum = 0;

		int kNum = 0;

		for (TreeObj treeObj : nodeList) {

			if ("L".equals(treeObj.getType())) {

				categoryNum++;

				treeObj.setSort(categoryNum);

			} else if ("T".equals(treeObj.getType())) {

				tableNum++;

				treeObj.setSort(tableNum);

			} else if ("M".equals(treeObj.getType())) {

				colNum++;

				treeObj.setSort(colNum);

			} else if ("K".equals(treeObj.getType())) {

				kNum++;
				treeObj.setSort(kNum);
			}

		}

		sContentInfo.setColNum(colNum);
		sContentInfo.setTableNum(tableNum);
		sContentInfo.setCategoryNum(categoryNum);
		sContentInfoDao.insert(sContentInfo);
		sContentDao.add(nodeList, sContentInfo.getId());

	}

	@Override
	public SContentInfo getScontentInfo(int id) {

		return sContentInfoDao.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public void deleteScontent(int id) {
		sContentInfoDao.deleteByPrimaryKey(id);
		sContentDao.delByInfoId(id);

	}

	@Override
	public Map<String, Object> getDetail(String kId, String tybm, String scotnetType, SysUser userInfo) {

		Map<String, Object> result = new HashMap<String, Object>();

		List<TableResult> tableList = sContentDao.selectSsearchResource(kId, scotnetType);

		// 一站式查询添加共享目录权限控制
		if (null != userInfo && "YZS".equals(scotnetType)) {
			Long topDeptId = userInfo.getOfficeId();
			String pIds = userInfo.getAllParentId();
			if (StringUtils.isNotBlank(pIds)) {
				String t = StringUtils.split(pIds, ",")[0];
				topDeptId = StringUtils.isNotBlank(t) ? Long.valueOf(t) : topDeptId;
			}
			List<String> resources = shareResourceService.getShareResource(topDeptId);
			// 共享资源不为空
			if (!CollectionUtils.isEmpty(resources) && !CollectionUtils.isEmpty(tableList)) {
				for (Iterator<TableResult> i = tableList.iterator(); i.hasNext();) {
					TableResult t = i.next();
					// 表有权限进行字段权限判断
					if (null != t && resources.contains(t.getTableId())) {
						List<Column> columns = t.getColumns();
						if (!CollectionUtils.isEmpty(columns)) {
							for (Iterator<Column> j = columns.iterator(); j.hasNext();) {
								Column column = j.next();
								// 判断字段是否有权限，没权限删除
								if (!resources.contains(String.valueOf(column.getMetricId()))) {
									j.remove();
								}
							}
							// 字段删光了，表删除
							if (CollectionUtils.isEmpty(columns)) {
								i.remove();
							}
						} else {
							// 没有查询字段，删除
							i.remove();
						}
					} else {
						// 表没权限，删除
						i.remove();
					}
				}
			}
		}
		Set<String> categorySet = new HashSet<String>();

		for (TableResult tableResult : tableList) {
			try {

				String categoryName = tableResult.getCategoryName();

				if (StringUtils.isNotBlank(categoryName)) {

					categorySet.add(categoryName);

				}

				if (!CollectionUtils.isEmpty(tableResult.getColumns())) {

					List<DataResult> filter = new ArrayList<DataResult>();

					List<DataResult> data = tableService.getData("t_" + tableResult.getTableNameEN(),
							tableResult.getColumns(), tybm);
					if ("XYHC".equals(scotnetType)) {

						for (DataResult res : data) {

							if (!RecordStatusEnum.FIX.getValue().equals(res.getStatus())) {
								filter.add(res);
							}
						}

						tableResult.setData(filter);

					} else {

						tableResult.setData(data);
					}

				}
			} catch (Exception e) {

				ExceptionLogger.error(e);

			}

			// tableResult.setColumns(null);

		}

		result.put("results", tableList);

		result.put("category", StringUtils.join(categorySet.toArray(), " "));

		return result;

	}

	@Override
	public List<SContentInfo> getListForPage(String name, Page page) {

		return sContentInfoDao.getListForPage(name, page);
	}

	@Override
	public List<String> getScontentName() {

		return sContentInfoDao.getScontentName();
	}

	@Override
	public List<TreeObj> getEditDeatil(int infoId) {

		return sContentDao.selectEditDetail(infoId);
	}

	@Override
	public List<TreeObj> getSharingContentTree(String infoId) {

		return sContentDao.selectSharingContentTree(infoId);
	}

	@Override
	public SContentInfo getInfoDeatil(int infoId) {

		return sContentInfoDao.selectByPrimaryKey(infoId);

	}

	@Override
	public boolean typeExist(String type) {
		// TODO Auto-generated method stub
		return sContentInfoDao.selectByType(type) > 0;
	}

	/**
	 * 
	 * @Function 数据共享子系统看板共享目录数据 按类型查询
	 * @Date 2018年4月26日 下午5:26:48
	 * @Author Min DongXv
	 * @param type
	 *            YZS:一站式,XYHC:信用核查,JKSQ:接口授权
	 * @return
	 */
	@Override
	public SContentInfo getCountShareContentInfo(String type) {
		return sContentInfoDao.getCountShareContentInfo(type);
	}

	@Override
	@Transactional
	public void updateScontent(SContentInfo sContentInfo, List<TreeObj> nodeList) {

		int tableNum = 0;

		int colNum = 0;

		int categoryNum = 0;

		int kNum = 0;

		for (TreeObj treeObj : nodeList) {

			if ("T".equals(treeObj.getType())) {

				tableNum++;

				treeObj.setSort(tableNum);

			} else if ("M".equals(treeObj.getType())) {

				colNum++;

				treeObj.setSort(colNum);

			} else if ("L".equals(treeObj.getType())) {

				categoryNum++;

				treeObj.setSort(categoryNum);

			} else if ("K".equals(treeObj.getType())) {
				kNum++;
				treeObj.setSort(kNum);

			}

		}
		sContentInfo.setTableNum(tableNum);
		sContentInfo.setColNum(colNum);
		sContentInfo.setCategoryNum(categoryNum);
		sContentDao.updateSContent(sContentInfo);
		sContentDao.delByInfoId(sContentInfo.getId());
		sContentDao.add(nodeList, sContentInfo.getId());
	}

	@Override
	public List<TreeObj> getSharingContentTreeByType(String type) {
		return sContentDao.selectSharingContentTreeByType(type);
	}

	/**
	 * 
	 *
	 * @Function 获取共享内容信息
	 * @FileName ScontentServiceImpl.java
	 * @MethodName getShareContent
	 * @param type
	 * @return
	 * @Date 2018年9月11日 下午7:09:56
	 * @Author Min DongXv
	 *
	 */
	@Override
	public SContentInfo getShareContent(String type) {
		return sContentInfoDao.getShareContentByType(type);
	}

	@Override
	public Map<String, Object> getriskdata(String tybm, String keyWord) {
		Map<String, Object> datamap = new HashMap<>();
		Map<String, Object> uniqueriskmap = new HashMap<>();
		//关联风险处罚数据
		List<Map<String,String>> uniqueriskCfdatas = new ArrayList<Map<String,String>>();
		//关联风险黑名单数据
		List<Map<String,String>> uniqueriskHeidatas = new ArrayList<Map<String,String>>();
		//关联风险重大税收违法案件
		List<Map<String,String>> uniqueriskZdsswfdatas = new ArrayList<Map<String,String>>();
		//关联风险失信被执行人
		List<Map<String,String>> uniqueriskSxbzxrdatas = new ArrayList<Map<String,String>>();
		//关联风险经营异常名录
		List<Map<String,String>> uniqueriskJyycdatas = new ArrayList<Map<String,String>>();
		
		//关联提示数据
		//List<Map<String,Object>> uniqueTipsdatas = new ArrayList<Map<String,Object>>();
		
		//获取自身风险数据失信被执行人(高风险)数据  100000480022_l7l5N1T4Y1）
		List<Map<String,String>> OneselfriskSxbzxrdata = sContentDao.getOneselfRiskdata(keyWord);
		//获取自身风险数据重大税收违法案件
	   List<Map<String,String>> OneselfriskZdwfsjdata = sContentDao.getOneselfriskheitata(keyWord);
	   //获取自身风险数据黑名单
	   List<Map<String,String>> Oneselfriskhmddata = sContentDao.getOneselfriskhmdtata(keyWord);
	   //获取自身风险数据行政处罚
	   List<Map<String,String>> Oneselfriskxzcfdata = sContentDao.getOneselfriskxzcftata(keyWord);
	   //获取自身风险数据经营异常名录
	   List<Map<String,String>> Oneselfriskjyycmldata = sContentDao.getOneselfriskjyycmltata(keyWord);
		//获取自身风险数量
	   int OneselfCount = OneselfriskSxbzxrdata.size()+OneselfriskZdwfsjdata.size()+Oneselfriskhmddata.size()+Oneselfriskxzcfdata.size()+Oneselfriskjyycmldata.size();
	   //关联风险数
	   int uniqueRiskCount = 0;
	   //提示信息数
	   int TipsCount = 0;
	   
	   //获取自身提示信息
	 //  List<Map<String,String>> OneselfriskTipsdata = sContentDao.getOneselfriskTipsdata(keyWord);
	 //获取自身提示信息的类别
	   List<String> types = sContentDao.getgetOneselfriskTipsType();
	   Map<String,Object> OneselfriskTipsdata  = new HashMap<>();
	//获取自身提示信息
	   if(!types.isEmpty()) {		    
	   for(String type:types) {
		   List<Map<String,String>> Tipsdata = sContentDao.getOneselfriskTipsdata(type,keyWord);
		   OneselfriskTipsdata.put(type, Tipsdata);
		   TipsCount = TipsCount +Tipsdata.size();
	   }
	   }
		//获取该企业对应的关联企业
		List<Map<String,String>> uniquedatas = sContentDao.getuniquedatas(keyWord);
		for(Map map : uniquedatas) {
			//获取该企业对应关联的企业风险行政处罚数据
			keyWord = map.get("A000001").toString();
			List<Map<String,String>> uniqueriskSxbzxrdata = sContentDao.getOneselfRiskdata(keyWord);
			//获取该企业对应关联的企业失信被执行人(高风险)数据
			List<Map<String,String>> uniqueriskZdwfsjdata = sContentDao.getOneselfriskheitata(keyWord);
			 //获取该企业对应关联的企业风险数据黑名单
			   List<Map<String,String>> uniqueriskhmddata = sContentDao.getOneselfriskhmdtata(keyWord);
			   //获取该企业对应关联的企业风险数据行政处罚
			   List<Map<String,String>> uniqueriskxzcfdata = sContentDao.getOneselfriskxzcftata(keyWord);
			   //获取该企业对应关联的企业风险数据经营异常名录
			   List<Map<String,String>> uniqueriskjyycmldata = sContentDao.getOneselfriskjyycmltata(keyWord);									
			uniqueRiskCount =uniqueRiskCount+ uniqueriskSxbzxrdata.size()+uniqueriskZdwfsjdata.size()+uniqueriskhmddata.size()+uniqueriskxzcfdata.size()+uniqueriskjyycmldata.size();
			//TipsCount = TipsCount+uniquedataTipsdata.size();			
			uniqueriskCfdatas.addAll(uniqueriskxzcfdata);
			uniqueriskHeidatas.addAll(uniqueriskhmddata);
			uniqueriskZdsswfdatas.addAll(uniqueriskZdwfsjdata);
			uniqueriskSxbzxrdatas.addAll(uniqueriskSxbzxrdata);
			uniqueriskJyycdatas.addAll(uniqueriskjyycmldata);
		//	uniqueTipsdatas.addAll(uniquedataTipsdata);			
	}
	
		datamap.put("OneselfriskSxbzxrdata", OneselfriskSxbzxrdata);
		datamap.put("OneselfriskZdwfsjdata", OneselfriskZdwfsjdata);
		datamap.put("Oneselfriskhmddata", Oneselfriskhmddata);
		datamap.put("Oneselfriskxzcfdata", Oneselfriskxzcfdata);
		datamap.put("Oneselfriskjyycmldata", Oneselfriskjyycmldata);
		
		datamap.put("OneselfriskTipsdata", OneselfriskTipsdata);
		datamap.put("uniqueriskCfdatas", uniqueriskCfdatas);
		datamap.put("uniqueriskHeidatas", uniqueriskHeidatas);
		datamap.put("uniqueriskZdsswfdatas", uniqueriskZdsswfdatas);
		datamap.put("uniqueriskSxbzxrdatas", uniqueriskSxbzxrdatas);
		datamap.put("uniqueriskJyycdatas", uniqueriskJyycdatas);

		datamap.put("OneselfCount", OneselfCount);
		datamap.put("uniqueRiskCount", uniqueRiskCount);
		datamap.put("TipsCount", TipsCount);
		return datamap;
	}

	@Override
	public List<Map<String, Object>> getcreditInfoSelectByLikeForPage(String param, String tablename, String range,
			Page page) {
		
		return sContentDao.getcreditInfoSelectByLikeForPage(param,tablename,range,page);
	}

	@Override
	public List<Map<String, Object>> getcreditInfoSelectByAccurateForPage(String param, String tablename, String range,
			Page page) {
		return sContentDao.getcreditInfoSelectByAccurateForPage(param,tablename,range,page);
	}

	@Override
	public List<Map<String, Object>> getFQYFRcreditInfoSelectByLikeForPage(String param, String tablename, String range,
			Page page) {
		return sContentDao.getFQYFRcreditInfoSelectByLikeForPage(param,tablename,range,page);
	}

	@Override
	public List<Map<String, Object>> getFQYFRcreditInfoSelectByAccurateForPage(String param, String tablename,
			String range, Page page) {
		return sContentDao.getFQYFRcreditInfoSelectByAccurateForPage(param,tablename,range,page);
	}

	
	
	@Override
	public List<Map<String, Object>> getcreditInfoLikeForPage(String param, String tablename, String range, Page page) {
		return sContentDao.getcreditInfoLikeForPage(param,tablename,range,page);
	}
}
